#include "srmediaplayer.h"
#include "ui_srmediaplayer.h"
#include "mediaplaylist.h"
#include "controlwidget.h"

#include <QMediaPlayer>
#include <QFileDialog>
#include <QSlider>
#include <QAudioOutput>
#include <QMessageBox>
#include <QMouseEvent>

SRMediaPlayer::SRMediaPlayer(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::SRMediaPlayer)
{
    ui->setupUi(this);

    setWindowTitle("SR音视频播放器");   // 设置窗口标题
    controlwidget = nullptr;

    // 建立对象
    qPlayer = new QMediaPlayer;                        // 播放器对象
    qPlaylist = new MediaPlaylist(this);               // 创建播放列表的对象
    qVideoWidget = new QVideoWidget(ui->VideoWidget);  // 播放窗口对象

    // 为 VideoWidget 安装事件过滤器
    ui->VideoWidget->installEventFilter(this);

    // 设置播放器窗口
    qPlayer->setVideoOutput(qVideoWidget);
    QAudioOutput *audioOutput = new QAudioOutput; // 创建音频输出对象
    qPlayer->setAudioOutput(audioOutput);         // 将音频输出对象绑定到播放器
    // 设置初始音量为 50
    qPlayer->audioOutput()->setVolume(50);

    // 初始化 ControlWidget
    controlwidget = new ControlWidget(this); // 创建 ControlWidget 并传入主窗口指针
    controlwidget->installEventFilter(this); // 安装事件过滤器

    // 信号与槽
    connect(qPlayer, &QMediaPlayer::positionChanged, this, &SRMediaPlayer::on_positionChanged); // 连接播放位置变化信号
    connect(qPlayer, &QMediaPlayer::durationChanged, this, &SRMediaPlayer::on_durationChanged); // 连接视频总时长变化信号
    connect(controlwidget, &ControlWidget::volumeChanged, this, &SRMediaPlayer::setVolume);  // 音量设置
}

// 媒体播放器的播放位置变化
void SRMediaPlayer::on_positionChanged(qint64 position)
{
    emit progressSliderValueChanged(static_cast<int>(position)); // 发出信号
}

// 播放器的总时长变化
void SRMediaPlayer::on_durationChanged(qint64 duration)
{
    emit durationChanged(duration); // 发出信号
}

void SRMediaPlayer::paintEvent(QPaintEvent *e)
{
    qVideoWidget->resize(ui->VideoWidget->size());
}

SRMediaPlayer::~SRMediaPlayer()
{
    delete ui;
    delete qPlayer;
    delete qVideoWidget;
    delete qPlaylist;
    delete controlwidget;
}

void SRMediaPlayer::on_BrowseButton_clicked()
{
    QStringList filenames = QFileDialog::getOpenFileNames(this, "你的电脑可否有好看的视频？",
                                                          "C:/Users/Administrator/Desktop",
                                                          "allfiles(*.*);;MP4(*.mp4);;MP3(*.mp3);;MKV(*.mkv);;AVI(*.AVI)");

    if (!filenames.isEmpty()) {
        foreach (QString filename, filenames) {
            QUrl url = QUrl::fromLocalFile(filename);
            qPlaylist->addMedia(url);
        }
    }
}

void SRMediaPlayer::on_PlayButton_clicked()
{
    if (!qPlaylist->isEmpty()) {
        if (qPlayer->playbackState() == QMediaPlayer::PausedState) {
            qPlayer->play();
        } else {
            QUrl nextMedia = qPlaylist->currentMedia();
            updateFilenameDisplay(nextMedia);
            qPlayer->setSource(nextMedia);
            qPlayer->play();
        }
    }
}

void SRMediaPlayer::on_PauseButton_clicked()
{
    qPlayer->pause();
}

void SRMediaPlayer::on_NextButton_clicked()
{
    if (!qPlaylist->isEmpty()) {
        qPlaylist->next();
        QUrl currentMedia = qPlaylist->currentMedia();
        updateFilenameDisplay(currentMedia);
        qPlayer->setSource(currentMedia);
        qPlayer->play();
    } else {
        QMessageBox::warning(this, "警告", "播放列表为空！");
    }
}

void SRMediaPlayer::on_PreviousButton_clicked()
{
    if (!qPlaylist->isEmpty()) {
        qPlaylist->previous();
        QUrl currentMedia = qPlaylist->currentMedia();
        updateFilenameDisplay(currentMedia);
        qPlayer->setSource(currentMedia);
        qPlayer->play();
    } else {
        QMessageBox::warning(this, "警告", "播放列表为空！");
    }
}

void SRMediaPlayer::updateFilenameDisplay(const QUrl &media)
{
    if (!media.isEmpty()) {
        QString filename = media.toLocalFile();
        ui->FilenameEdit->setText(filename);
    } else {
        ui->FilenameEdit->clear();
    }
}

// 实现播放器进度条的控制
void SRMediaPlayer::on_sliderMoved(int position)
{
    qPlayer->setPosition(position);   // 将播放器的播放位置跳转到该时间点
}

// 保持控制界面大小与主界面一致
void SRMediaPlayer::resizeEvent(QResizeEvent *event)
{
    QMainWindow::resizeEvent(event);
    if (controlwidget != nullptr) {
        controlwidget->setGeometry(this->geometry());
    }
}

// 保持控制界面位置与主界面一致
void SRMediaPlayer::moveEvent(QMoveEvent *event)
{
    QMainWindow::moveEvent(event);
    if (controlwidget != nullptr) {
        controlwidget->setGeometry(this->geometry());
    }
}

// 通过单击播放器来开关控制窗口
bool SRMediaPlayer::eventFilter(QObject *obj, QEvent *event)
{
    if (obj == ui->VideoWidget && event->type() == QEvent::MouseButtonPress) {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
        if (mouseEvent->button() == Qt::LeftButton) {
            // 鼠标左键点击 VideoWidget 时切换控制窗口的显示状态
            if (controlwidget) {
                bool isVisible = controlwidget->isVisible();
                controlwidget->setVisible(!isVisible);
            }
            return true; // 表示事件已被处理
        }
    }
    return QMainWindow::eventFilter(obj, event); // 调用基类的事件过滤器
}

// 音量设置
void SRMediaPlayer::setVolume(int volume)
{
    if (qPlayer && qPlayer->audioOutput()) {
        qPlayer->audioOutput()->setVolume(volume);  // 设置音频输出的音量
    }
}
